#include "glwidget.h"
#include <QPainter>
#include <QPaintEngine>

#define texSize 200

GLfloat vertices[] = {
	-1.0, -1.0, 0.0,
	-1.0, 1.0, 0.0,
	1.0, 1.0, 0.0,

	1.0, 1.0, 0.0,
	1.0, -1.0, 0.0,
	-1.0, -1.0, 0.0
};

GLfloat texCoord[] = {
	0.0, 0.0,
	0.0, 1.0,
	1.0, 1.0,
	1.0, 1.0,
	1.0, 0.0,
	0.0, 0.0
};

GLWidget::GLWidget(QWidget *parent) : QGLWidget(parent) {
	setAttribute(Qt::WA_PaintOnScreen);
	setAttribute(Qt::WA_NoSystemBackground);
	setAutoBufferSwap(false);
	#ifndef Q_WS_QWS
		setMinimumSize(300, 250);
	#endif
}

GLWidget::~GLWidget() {
}

void GLWidget::initializeGL() {
	xParam = new QGLFramebufferObject(texSize, texSize);
	yParam = new QGLFramebufferObject(texSize, texSize);

	QGLShader *vshader = new QGLShader(QGLShader::Vertex);
	vshader->compileSourceFile("vertex.shader");
	QGLShader *fshader = new QGLShader(QGLShader::Fragment);
	fshader->compileSourceFile("fragment.shader");
	program.addShader(vshader);
	program.addShader(fshader);
	program.link();

	vertexAttr = program.attributeLocation("vertex");
	texCoordAttr = program.attributeLocation("texCoord");
	matrixUniform = program.uniformLocation("matrix");
	textureUniform = program.uniformLocation("tex");
}

void GLWidget::paintGL() {
	QPainter painter(yParam);
	QColor penColor = QColor(255,255,255);
	QPen pen = QPen(penColor);
	pen.setWidth(1);
	painter.setPen(pen);
	painter.drawEllipse(50,50,50,50);
	painter.end();

	painter.begin(this);
	painter.beginNativePainting();
		glMatrixMode(GL_PROJECTION);
		glClearColor(0.1f, 0.1f, 0.2f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

		QMatrix4x4 modelview;
		modelview.ortho(QRect(0.0, texSize, 0.0, texSize));
		glViewport(0, 0, texSize, texSize);

		program.bind();
		program.setUniformValue(matrixUniform, modelview);

		glBindTexture(GL_TEXTURE_2D, xParam->texture());
		glBindTexture(GL_TEXTURE_2D, yParam->texture());

		program.setAttributeArray(vertexAttr, vertices, 3);
		program.setAttributeArray(texCoordAttr, texCoord, 2);

		program.setUniformValue(textureUniform, 0);

		program.enableAttributeArray(vertexAttr);
		program.enableAttributeArray(texCoordAttr);

		glDrawArrays(GL_TRIANGLES, 0, 6);

		program.disableAttributeArray(vertexAttr);
		program.disableAttributeArray(texCoordAttr);

		program.release();
	painter.endNativePainting();

	swapBuffers();
}
